#include "AspectEngine.h"

namespace agtk {

bool WriteString(std::string t_str, FILE* t_fp) {
	// Does the file stream exist and is it valid? If not, return false.
	if (t_fp == NULL) return false;

	// Create char pointer from string.
	char* text = const_cast<char*>(t_str.c_str());
	
	// Find the length of the string.
	unsigned int size = t_str.size();
	
	// Write the string's size to the file.
	fwrite(&size, sizeof(unsigned int), 1, t_fp);
	
	// Followed by the string itself.
	fwrite(text, 1, size, t_fp);

	// Everything worked, so return true.
	return true;
}

std::string ReadString(FILE* t_fp) {
	// Does the file stream exist and is it valid? If not, return false.
	if (t_fp == NULL) return false;
	
	// Create new string object to store the retrieved text and to return to the calling function.
	std::string str;
	
	// UInt for storing the string's size.
	unsigned int size;

	// Read the size of the string from the file and store it in size.
	fread(&size, sizeof(unsigned int), 1, t_fp);
	
	// Create a char pointer for temporary storage.
	char* text = new char[size];
	
	// Read [size] number of characters from the string and store them in text.
	fread(text, 1, size, t_fp);
	
	// Store the contents of text in str.
	str = text;
	
	// Free the temporary storage
	delete[] text;
	
	// Resize str to match the size else we get extra cruft (line endings methinks).
	str.resize(size);

	// Finally, return the string to the calling function.
	return str;
}

char *ReadEntireFile(char *fn) {
	FILE *fp;
	char *content = NULL;
	int count=0;
	
	if (fn != NULL) {
		fp = fopen(fn,"rt");
		if (fp != NULL) {
       	      		fseek(fp, 0, SEEK_END);
       			count = ftell(fp);
       			rewind(fp);
			if (count > 0) {
				content = (char *)malloc(sizeof(char) * (count+1));
				count = fread(content,sizeof(char),count,fp);
				content[count] = '\0';
			}
			fclose(fp);
		}
	}
	return content;
}

}